package com.lancoo.klgcourseware.ui.fragment.repeat;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import android.text.SpannableString;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.lzyzsd.circleprogress.DonutProgress;
import com.lancoo.klgcourseware.R;
import com.lancoo.klgcourseware.base.BaseKlgFragment;
import com.lancoo.klgcourseware.entity.WordPracticeModel;
import com.lancoo.klgcourseware.ui.fragment.basicTrain.BasicTrainBaseFragment;
import com.lancoo.klgcourseware.ui.widget.CountTimeView;
import com.lancoo.klgcourseware.utils.KlgTrainUtils;
import com.lancoo.klgcourseware.utils.KlgTimeUtils;
import com.stkouyu.entity.LgEvaluateObj;
import com.tt.LancooSkEgnManager;

/**
 * 该子fragment只作相关的UI变动,所有交互逻辑基本扔回上一层fragment
 * {@link com.lancoo.klgcourseware.ui.fragment.basicTrain.RepeatTrainFragment}
 */
public class RepeatChildFragment extends BaseKlgFragment {

    private static final String EXTRA_REPEAT_TRAIN_MODEL = "repeat_model";

    private static final String EXTRA_REPEAT_TRAIN_FROM = "repeat_from";

    private static final String EXTRA_REPEAT_TRAIN_LAST = "repeat_last";

    private final int MODE_PRE_TRAINT = 0x00;

    private final int MODE_FIRST_PLAYING = 0x01;

    private final int MODE_RECORDING = 0x02;

    private final int MODE_EVALUATING = 0x03;

    private final int MODE_EVALUATION_PASS = 0x04;

    private final int MODE_EVALUATION_FAIl = 0x05;

    private final int MODE_FAIL_REPLAYING = 0x06;

    private Context mContext;

    private int mMode = MODE_PRE_TRAINT;

    private int mPendingMode = MODE_PRE_TRAINT;

    private int mLastCountHelper = 0;

    private SpannableString mSentence; //原文

    private TextView mTvContent;

    private TextView mTvHiddenHint;

    private TextView mTvPlayTime;

    private TextView mTvAlert;

    private View mActionAbort; //我不练了

    private TextView mTvPass;

    private WordPracticeModel mModel;

    private boolean mIsLast;

    private boolean mIsFromMore;

    private View mGroupRecord; //录音区域

    private ImageView mImgPauseHint; //暂停提示图

    private View mGroupSoundPlay; //播放原声区域

    private View mGroupEvaluationPass; //测评通过区域

    private View mGroupSystemClock; //倒计时时钟

    private DonutProgress mDonutProgress;

    private CountTimeView mCountTimeView;

    private int mScore;

    private long mLastInputTime;
    private boolean mHasInput = false;//录音分贝检测辅助

    private long mLastRecordingTime;

    public static RepeatChildFragment newInstance(WordPracticeModel wordPracticeModel,boolean isLast,boolean isFromMore) {
        RepeatChildFragment childFragment = new RepeatChildFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable(EXTRA_REPEAT_TRAIN_MODEL, wordPracticeModel);
        bundle.putBoolean(EXTRA_REPEAT_TRAIN_FROM, isFromMore);
        bundle.putBoolean(EXTRA_REPEAT_TRAIN_LAST, isLast);
        childFragment.setArguments(bundle);
        return childFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mContext = null;
    }

    public void onSystemClockTimer(int progress, int totalProgress) {
        mCountTimeView.setAngle(progress, totalProgress);
        if (mMode == MODE_EVALUATION_FAIl
                && progress >= totalProgress) {
            mMode = MODE_FAIL_REPLAYING;
            changeModeUI();
            onDripComplete();
        } else if (mMode == MODE_EVALUATION_PASS
                && progress >= totalProgress) {

            if (getParentFragment() instanceof BasicTrainBaseFragment) {
                ((BasicTrainBaseFragment) getParentFragment()).pauseTimer();
                ((BasicTrainBaseFragment) getParentFragment()).startNextQuesTraion();
            }
        }
    }

    public void onTrainStart() {
        if (mMode != MODE_FAIL_REPLAYING) {
            mMode = MODE_FIRST_PLAYING;
            changeModeUI();
        }
        mCountTimeView.setAngle(0, 1000);
        startAnimation();
    }

    public void onRecordFinish(){
        if (getParentFragment() instanceof BasicTrainBaseFragment) {
            ((BasicTrainBaseFragment) getParentFragment()).pauseTimer();
            ((BasicTrainBaseFragment) getParentFragment()).stopRecordSpeechEvaluation();
        }

        mHasInput = false;
        mMode = MODE_EVALUATING;
        changeModeUI();
    }

    private void onTrainPass() {
        mMode = MODE_EVALUATION_PASS;
        mTvContent.setTextColor(ContextCompat.getColor(mContext, R.color.klg_quality_color));
        mTvContent.setText(mSentence.toString());
        changeModeUI();

        if (getParentFragment() instanceof BasicTrainBaseFragment) {
            ((BasicTrainBaseFragment) getParentFragment()).startSecondCountTime();
            ((BasicTrainBaseFragment) getParentFragment()).usageQuesTrainResultMediaPlayer(true);
        }
    }

    private void onTrainFail() {
        mMode = MODE_EVALUATION_FAIl;
        mTvContent.setTextColor(ContextCompat.getColor(mContext, R.color.klg_black));
        mTvContent.setText(mSentence);
        changeModeUI();

        if (getParentFragment() instanceof BasicTrainBaseFragment) {
            mLastCountHelper = 0;
            ((BasicTrainBaseFragment) getParentFragment()).startSecondCountTime(); //倒计时3s进入下一级别
            ((BasicTrainBaseFragment) getParentFragment()).usageQuesTrainResultMediaPlayer(false);
        }
    }

    public void onTrainError(String error) {

    }

    public void pauseTrain(boolean isReset) {

        stopAnimation();
        audioAnimation(0);
        mCountTimeView.setAngle(0, 1000);
        if (isReset){
            mMode = MODE_PRE_TRAINT;
            mPendingMode = MODE_PRE_TRAINT;
            mCountTimeView.setAngle(0, 1000);
            mImgPauseHint.setVisibility(View.GONE);
            changeModeUI();
        }else {
            mPendingMode =  mMode;
            mGroupSystemClock.setVisibility(View.GONE);
            mGroupSoundPlay.setVisibility(View.GONE);
            mGroupEvaluationPass.setVisibility(View.GONE);
            mGroupRecord.setVisibility(View.GONE);
            mImgPauseHint.setVisibility(View.VISIBLE);
        }
        mTvPlayTime.setText(getString(R.string.klg_repeat_play_time, "00:00"));
        mTvAlert.setText(getString(R.string.klg_repeat_prepare));

        if (getParentFragment() instanceof BasicTrainBaseFragment) {
            ((BasicTrainBaseFragment) getParentFragment()).pauseTimer();
        }

    }

    public void processTrain() {
        mImgPauseHint.setVisibility(View.GONE);
        mMode = mPendingMode;
        changeModeUI();

        switch (mMode){
            case MODE_PRE_TRAINT:
                if (getParentFragment() instanceof BasicTrainBaseFragment) {
                    ((BasicTrainBaseFragment) getParentFragment()).startTrainDialogCountTime(0);
                }

            case MODE_EVALUATING:
                break;
            case MODE_FIRST_PLAYING:
            case MODE_FAIL_REPLAYING:
                onDripComplete();
                break;
            case MODE_RECORDING:
                onRecordProgressUpdate(-1);
                break;
            case MODE_EVALUATION_PASS:
                onTrainPass();
                break;
            case MODE_EVALUATION_FAIl:
                onTrainFail();
                break;
        }

    }

    public void resetTrain() {
        pauseTrain(true);
//        processTrain();
    }

    public void onDripComplete() {
        if (mMode == MODE_PRE_TRAINT
                || mMode == MODE_FIRST_PLAYING
                || mMode == MODE_FAIL_REPLAYING) {
            if (getParentFragment() instanceof BasicTrainBaseFragment) {
                mLastCountHelper = 0;
                ((BasicTrainBaseFragment) getParentFragment()).playDemonstrationSound(0);
//                ((BasicTrainBaseFragment) getParentFragment()).startSecondCountTime();
            }
        } else if (mMode == MODE_RECORDING) {
            if (getParentFragment() instanceof BasicTrainBaseFragment) {
                ((BasicTrainBaseFragment) getParentFragment()).pauseTimer();
                ((BasicTrainBaseFragment) getParentFragment()).startRecordSpeechEvaluation("", mSentence.toString());
            }
        }
    }

    //1s定时器更新
    public void onMediaProgressUpdate(int progress) {
        if (mMode == MODE_FIRST_PLAYING || mMode == MODE_FAIL_REPLAYING) {
            mLastCountHelper++;
            mTvPlayTime.setText(getString(R.string.klg_repeat_play_time, KlgTimeUtils.getTimeMinAndSecond(progress/1000)));
        }
    }

    public void onTrainEvaluationSuccess(int grade, LgEvaluateObj skegnResult) {

        mScore = grade;
        if (grade >= 85) {
            onTrainPass();
        } else {
            mSentence = KlgTrainUtils.getEvaluationResultSentence(mContext, mSentence.toString(),mModel, skegnResult);
            onTrainFail();
        }
    }

    /**
     * 录音进度通知
     *
     * @param progress -1表示要切换为录音模式
     */
    public void onRecordProgressUpdate(int progress) {

        if (progress < 0) {
            Log.e("Train", "preTrain");
            mHasInput = false;
            stopAnimation();
            audioAnimation(0);
            mMode = MODE_RECORDING;
            mLastRecordingTime = System.currentTimeMillis();
            changeModeUI();
            mDonutProgress.setMax(getRecordTime());
            mDonutProgress.setProgress(0);
            mTvPlayTime.setText(getString(R.string.klg_repeat_play_time, "00:00"));
            if (getParentFragment() instanceof BasicTrainBaseFragment) {
                ((BasicTrainBaseFragment) getParentFragment()).startDripMusic();
            }
        }else {
            mDonutProgress.setProgress(progress);

            if (progress >= mDonutProgress.getMax()) { //时间到了结束录音
                stopAnimation();
                onRecordFinish();
            }

            float volume = LancooSkEgnManager.getInstance(getContext()).getVolume();
            if (volume<2){
                if (System.currentTimeMillis() - mLastInputTime > 450){
                    audioAnimation((int) volume);
                }

                if (mHasInput && System.currentTimeMillis() - mLastInputTime>3_000){
                    onRecordFinish(); //朗读停止了2s，结束录音
                }
            }else {
                if (System.currentTimeMillis() - mLastInputTime > 50){
                    audioAnimation((int) volume);
                }

                mHasInput = true;
                mLastInputTime = System.currentTimeMillis();
            }
        }

    }

    public int getScore(){
        return mScore;
    }

    private void startAnimation() {

        if (mMode == MODE_FIRST_PLAYING
                || mMode == MODE_FAIL_REPLAYING) {
            ImageView imgTrack01 = convertView.findViewById(R.id.img_track01);
            ImageView imgTrack02 = convertView.findViewById(R.id.img_track02);
            ImageView imgTrack03 = convertView.findViewById(R.id.img_track03);
            ImageView imgTrack04 = convertView.findViewById(R.id.img_track04);

            ((AnimationDrawable) imgTrack01.getDrawable()).start();
            ((AnimationDrawable) imgTrack02.getDrawable()).start();
            ((AnimationDrawable) imgTrack03.getDrawable()).start();
            ((AnimationDrawable) imgTrack04.getDrawable()).start();
//            return;
        }

//        if (mMode == MODE_RECORDING) {
//            ImageView img_recorder = convertView.findViewById(R.id.img_recorder);
//            if ( !((AnimationDrawable) img_recorder.getDrawable()).isRunning()){
//                ((AnimationDrawable) img_recorder.getDrawable()).start();
//            }
//        }

    }

    private void stopAnimation() {
        if (mMode == MODE_FIRST_PLAYING
                || mMode == MODE_FAIL_REPLAYING) {
            ImageView imgTrack01 = convertView.findViewById(R.id.img_track01);
            ImageView imgTrack02 = convertView.findViewById(R.id.img_track02);
            ImageView imgTrack03 = convertView.findViewById(R.id.img_track03);
            ImageView imgTrack04 = convertView.findViewById(R.id.img_track04);

            ((AnimationDrawable) imgTrack01.getDrawable()).stop();
            ((AnimationDrawable) imgTrack02.getDrawable()).stop();
            ((AnimationDrawable) imgTrack03.getDrawable()).stop();
            ((AnimationDrawable) imgTrack04.getDrawable()).stop();
//            return;
        }

//        if (mMode == MODE_RECORDING) {
//            ImageView img_recorder = convertView.findViewById(R.id.img_recorder);
//            if ( ((AnimationDrawable) img_recorder.getDrawable()).isRunning()){
//                ((AnimationDrawable) img_recorder.getDrawable()).stop();
//                ((AnimationDrawable) img_recorder.getDrawable()).selectDrawable(0);
//            }
//        }
    }

    private void audioAnimation(int db){
        try {
            ImageView imgRecorder = convertView.findViewById(R.id.img_recorder);
            LayerDrawable drawable =(LayerDrawable) imgRecorder.getDrawable();
            Drawable clipDrawable = drawable.getDrawable(1);

            clipDrawable.setLevel(KlgTrainUtils.getAudioDBLevel(db));
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private void changeModeUI() {
        if (mMode == MODE_PRE_TRAINT) {
            mTvAlert.setText(getString(R.string.klg_repeat_prepare));
        } else if (mMode == MODE_EVALUATION_FAIl) {
            mTvAlert.setText(getString(R.string.klg_repeat_evaluation_fail));
        }
        mGroupSoundPlay.setVisibility(mMode == MODE_FIRST_PLAYING || mMode == MODE_FAIL_REPLAYING
                ? View.VISIBLE : View.GONE);
        mGroupRecord.setVisibility(mMode == MODE_RECORDING ? View.VISIBLE : View.GONE);
        mGroupEvaluationPass.setVisibility(mMode == MODE_EVALUATION_PASS ? View.VISIBLE : View.GONE);
        mGroupSystemClock.setVisibility(mMode == MODE_PRE_TRAINT || mMode == MODE_EVALUATION_FAIl ? View.VISIBLE : View.GONE);
        mActionAbort.setVisibility(mMode == MODE_EVALUATION_FAIl ? View.VISIBLE : View.GONE);

        if (mMode == MODE_FIRST_PLAYING
                || mMode == MODE_RECORDING
                || mMode == MODE_EVALUATING
                || mMode == MODE_PRE_TRAINT) {
            mTvHiddenHint.setVisibility(View.VISIBLE);
            mTvContent.setVisibility(View.GONE);
        } else {
            mTvHiddenHint.setVisibility(View.GONE);
            mTvContent.setVisibility(View.VISIBLE);
        }

    }

    private void initData() {
        Bundle bundle = getArguments();

        if (bundle != null) {
            mModel = bundle.getParcelable(EXTRA_REPEAT_TRAIN_MODEL);
            mIsFromMore = bundle.getBoolean(EXTRA_REPEAT_TRAIN_FROM,false);
            mIsLast = bundle.getBoolean(EXTRA_REPEAT_TRAIN_LAST,false);
        }

        if (mModel != null) {
            mSentence = KlgTrainUtils.getRawSentence(mContext,mModel);
            mTvContent.setText(mSentence);
        }

        audioAnimation(0);

        mTvPlayTime.setText(getString(R.string.klg_repeat_play_time, "00:00"));
        mTvAlert.setText(getString(R.string.klg_repeat_prepare));

        if (mIsLast){
            mTvPass.setText(mIsFromMore?getString(R.string.klg_repeat_evaluation_more_pass):getString(R.string.klg_repeat_evaluation_last_pass));
        }else {
            mTvPass.setText(getString(R.string.klg_repeat_evaluation_pass));
        }

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        if (v.getId() == R.id.layout_recorder
                ||v.getId() == R.id.tv_end_record ){
            if (mMode == MODE_RECORDING && (System.currentTimeMillis() - mLastRecordingTime>1000)) //点击结束录音
                onRecordFinish();
        }else if (v.getId() == R.id.tv_pass_train){
            pauseTrain(true);
            if(getParentFragment() instanceof BasicTrainBaseFragment){
                ((BasicTrainBaseFragment) getParentFragment()).startNextQuesTraion();
            }
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.klg_fragment_child_repeat;
    }

    @Override
    protected void initView(View view) {
        mTvContent = view.findViewById(R.id.tv_content);
        mTvHiddenHint = view.findViewById(R.id.tv_hidden);
        mTvPass = view.findViewById(R.id.tv_evaluation_pass);
        mTvPlayTime = view.findViewById(R.id.tv_repeat_time);
        mTvAlert = view.findViewById(R.id.tv_spell_memory_write_alert);
        mActionAbort = view.findViewById(R.id.tv_pass_train);
        mGroupSoundPlay = view.findViewById(R.id.group_sound_play);
        mGroupRecord = view.findViewById(R.id.group_record);
        mGroupEvaluationPass = view.findViewById(R.id.group_pass);
        mDonutProgress = view.findViewById(R.id.donut_progress);
        mCountTimeView = view.findViewById(R.id.counttime_view);
        mGroupSystemClock = view.findViewById(R.id.layout_system_clock);
        mImgPauseHint = view.findViewById(R.id.img_pause_hint);

        view.findViewById(R.id.tv_pass_train).setOnClickListener(this);
        view.findViewById(R.id.layout_recorder).setOnClickListener(this);
        view.findViewById(R.id.tv_end_record).setOnClickListener(this);

        mTvContent.setMovementMethod(new ScrollingMovementMethod());
    }

    private int getRecordTime() {
        return  mModel.getIntVoiceTime() * 3;
    }
}
